<template>
	<!-- 生产详情页，用于单独工序的领料/退料/报工 -->
	<view>
		<uni-card :title="'生产工单：'+workOrder.number+'('+workOrder.processName+')'" :is-shadow="false" :isFull="true">
			<uni-row class="resourceList-uni-row">
				<uni-col :span="12">
					<text class="resourceList-text">
						产品:&nbsp;&nbsp;&nbsp;{{workOrder.materialName}}
					</text>
				</uni-col>
				<uni-col :span="12">
					<text class="resourceList-text">
						生产数量:&nbsp;&nbsp;&nbsp;{{workOrder.quantity}} &nbsp;&nbsp;&nbsp;({{workOrder.materialUnitName}})
					</text>
				</uni-col>
			</uni-row>
			<!--<uni-row class="resourceList-uni-row">
				<text class="resourceList-text">
					客户:&nbsp;&nbsp;&nbsp;{{workOrder.salOrder.customerName}}
				</text>
			</uni-row>
			<uni-row class="resourceList-uni-row">
				<uni-col :span="24">
					<uni-col :span="6"><text class="resourceList-text">规格型号:&nbsp;</text></uni-col>
					<uni-col :span="18">
						<uni-row v-for="(item,index) in workOrder.specification.split(',')">
							{{item}}
						</uni-row>
					</uni-col>
				</uni-col>
			</uni-row> -->
			<uni-row class="resourceList-uni-row">
				<uni-col :span="16">
					<text class="resourceList-text">
						计划完工:&nbsp;&nbsp;&nbsp;{{workOrder.planFinishDate}}
					</text>
				</uni-col>
				<uni-col :span="8">
					<text @click="fileDownload(workOrder)" style="text-decoration:underline">
						附件下载
					</text>
				</uni-col>
			</uni-row>
			<uni-row>
				<uni-col :span="24">
					<text class="resourceList-text">
						工单备注:&nbsp;&nbsp;&nbsp;{{workOrder.remark}}
					</text>
				</uni-col>
			</uni-row>
		</uni-card>
		<uni-section title="领料" type="line">
			<uni-card :is-shadow="false" :isFull="true">
				<view v-for="(item,index) in prickEntryList" :key="index" style="margin-top: 10rpx;">
					<uni-row>
						<uni-col :span="12">
							<text class="resourceList-text">
								{{item.pickMaterialName}}
							</text>
						</uni-col>
						<uni-col :span="12">
							<text class="resourceList-text">
								{{item.pickQuantity}}&nbsp;(卷)
							</text>
						</uni-col>
						<uni-row>
							<uni-col :span="18">
								<text class="resourceList-text">
									{{item.pickSpecification}}
								</text>
							</uni-col>
							<uni-col :span="4">
								<button style="padding: 0rpx; height: 57rpx;width: 85rpx;" plain="true" size="mini"
									type="primary" @click="clickPick(item.id)">
									<text style="font-size: 4;">领料</text>
								</button>
							</uni-col>
							<uni-col :span="2">
								<button style="padding: 0rpx; height: 57rpx;width: 85rpx;" plain="true" size="mini"
									type="primary" @click="clickInto(item.id)">
									<text style="font-size: 4;">退料</text>
								</button>
							</uni-col>
						</uni-row>

					</uni-row>

				</view>
			</uni-card>
		</uni-section>
		<uni-section title="报工" type="line">
			<uni-card :is-shadow="false" :isFull="true">
				<view v-for="(item,index) in reportEntryList" :key="index" style="margin-top: 10rpx;">
					<uni-row style="margin-bottom: 10rpx;">
						<uni-col :span="12">
							<text class="resourceList-text">
								{{item.reportMaterialName}}
							</text>
						</uni-col>
						<uni-col :span="12">
							<text class="resourceList-text">
								{{item.reportQuantity}}&nbsp;(卷)
							</text>
						</uni-col>
					</uni-row>
					<uni-row>
						<uni-col :span="12">
							<text class="resourceList-text">
								{{item.reportSpecification}}
							</text>
						</uni-col>
					</uni-row>

					<!-- 自定义扩展字段 -->
					<view v-for="(itemE,indexE) in entryFieldExtendList">
						<uni-row class="resourceList-uni-row">
							<text style="font-size: 14px;">
								{{itemE.fieldName}}:&nbsp;&nbsp;&nbsp;{{item.extendFieldJson[itemE.field]}}
							</text>
						</uni-row>
					</view>
					<uni-row>
						<text class="resourceList-text">
							备注:&nbsp;{{item.remark}}
						</text>
					</uni-row>
					<uni-row style="margin-top: 10rpx;">
						<uni-col :span="14">
							<text class="resourceList-text">
								设备:&nbsp;{{item.machineName}}
							</text>
						</uni-col>
						<uni-col :span="4">
							<button style="padding: 0rpx; height: 57rpx;width: 85rpx;" plain="true" size="mini"
								type="primary" @click="inputDialogToggle(item)" v-show="item.isShow">
								<text style="font-size: 4;">报工</text>
							</button>
						</uni-col>
						<uni-col :span="4">
							<button style="padding: 0rpx; height: 57rpx;width: 85rpx;" plain="true" size="mini"
								type="primary" @click="clickReportListPopup(item.id)" v-show="item.isShow">
								<text style="font-size: 4;">明细</text>
							</button>
						</uni-col>
						<uni-col :span="2">
							<button style="padding: 0rpx; height: 57rpx;width: 85rpx;" plain="true" size="mini"
								type="primary" @click="clickInto(item.id)">
								<text style="font-size: 4;">入库</text>
							</button>
						</uni-col>
					</uni-row>


				</view>
			</uni-card>
		</uni-section>
		<view>
			<!-- 报工新增输入框 -->
			<uni-popup ref="inputDialog" :mask-click="false">
				<view class="example">
					<!-- 基础用法，不包含校验规则 -->
					<uni-forms ref="baseForm" :modelValue="report">
						<uni-forms-item label="报工时间" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-datetime-picker type="datetime" v-model="report.reportTime" :clear-icon="false" />
						</uni-forms-item>
						<uni-forms-item label="报工人" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput v-model="report.reportUserName" :disabled="true" />
						</uni-forms-item>
						<uni-forms-item label="工序" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput v-model="report.processName" :disabled="true" />
						</uni-forms-item>
						<uni-forms-item label="半成品" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput v-model="report.reportMaterialName" :disabled="true" />
						</uni-forms-item>
						<uni-forms-item label="规格型号" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput v-model="report.reportSpecification" />
						</uni-forms-item>
						<uni-forms-item label="直接入库" required :labelWidth='80' class="uni-forms-item-bottom">
							<uni-data-select v-model="manufactureInto.warehouseId" :localdata="warehouseList"
								style="background-color: #fff;" @change="selectWarehouse">
							</uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="报工数量" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-row>
								<uni-col :span="20">
									<uni-easyinput v-model="report.reportQuantity" placeholder="请输入报工数量"
										:clearable="false" />
								</uni-col>
								<!-- <uni-col :span="4" style="padding-left: 8rpx;padding-top: 7rpx;">
									<uni-icons type="scan" size="32" @click="setScanShow"></uni-icons>
								</uni-col> -->
							</uni-row>
						</uni-forms-item>
						<uni-forms-item label="扫码SN码" :labelWidth='80' v-show="scanShow" style="margin-bottom: 5rpx; ">
							<uni-easyinput v-model="report.snArray" type="textarea"
								placeholder="请直接使用PDA扫描物料上的SN码"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="车间" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput v-model="report.workshopName" :disabled="true" />
						</uni-forms-item>
						<uni-forms-item label="工位" required :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput v-model="report.stationName" :disabled="true" />
						</uni-forms-item>
						<uni-forms-item label="工单备注" :labelWidth='80' style="margin-bottom: 5rpx;">
							<uni-easyinput type="textarea" v-model="report.remark" placeholder="请输入备注" />
						</uni-forms-item>
						<view class="button-group">
							<button type="primary" size="mini" @click="cancel()" plain="true">取消</button>
							<button type="primary" size="mini" @click="submit('baseForm')">提交</button>
						</view>
					</uni-forms>
				</view>
			</uni-popup>
		</view>
		<view>
			<uni-popup ref="reportLsitDialog" :mask-click="false">
				<view style="width: 700rpx;">
					<uni-section title="报工详情" type="line">
						<view class="resourceList">
							<view v-for="(item,index) in reportList" :key="index" style="margin-top: 10rpx;">

								<uni-row class="resourceList-uni-row">
									<text style="font-size: 14px;font-weight:bold;">
										报工单号:&nbsp;&nbsp;&nbsp;{{item.number}}
									</text>

								</uni-row>
								<!-- <uni-row class="resourceList-uni-row">
							<text style="font-size: 14px;">
							第:&nbsp;{{item.sort}}&nbsp;道---{{item.processName}}
							</text>
						</uni-row> -->
								<uni-row class="resourceList-uni-row">
									<text style="font-size: 14px;">
										报工时间&nbsp;&nbsp;&nbsp;{{item.reportTime}}
									</text>
								</uni-row>
								<uni-row class="resourceList-uni-row">
									<text style="font-size: 14px;">
										报工人:&nbsp;&nbsp;&nbsp;{{item.reportUserName}}
									</text>
								</uni-row>
								<uni-row class="resourceList-uni-row">
									<text style="font-size: 14px;">
										数量:&nbsp;&nbsp;&nbsp;{{item.reportQuantity}}
									</text>
								</uni-row>
								<!-- <uni-row class="resourceList-uni-row">
							<uni-col :span="6">
								<text style="font-size: 14px;">
								合格:&nbsp;&nbsp;&nbsp;{{item.qualifiedQuantity}}
								</text>
							</uni-col>
							<uni-col :span="6">
								<text style="font-size: 14px;">
								不合格:&nbsp;&nbsp;&nbsp;{{item.unqualifiedQuantity}}
								</text>
							</uni-col>
							<uni-col :span="12">
								<text style="font-size: 14px;">
								合格率:&nbsp;&nbsp;&nbsp;90&nbsp;%
								</text>
							</uni-col>
						</uni-row>
						<uni-row class="resourceList-uni-row">
							<text style="font-size: 14px;">
							报工车间:&nbsp;&nbsp;&nbsp;{{item.reportQuantity}}
							</text>
						</uni-row> -->
								<uni-row class="resourceList-uni-row">
									<text style="font-size: 14px;">
										报工工位:&nbsp;&nbsp;&nbsp;{{item.stationName}}
									</text>
								</uni-row>

								<uni-row style="margin-bottom: 35rpx;">
									<uni-col :span="19">
										<text style="font-size: 14px;">
											备注:&nbsp;&nbsp;&nbsp;{{item.remark}}
										</text>
									</uni-col>
									<!-- 具有质检权限的话显示‘增加质检’按钮 -->
									<!-- <view>
								<uni-col :span="5">
								<button style="padding: 0rpx; height: 57rpx;width: 120rpx;" plain="true"  size="mini" type="primary" @click="addReportQuality(item)">
									<text style="font-size: 4;">质检单</text>
								</button>
								</uni-col>
							</view> -->
								</uni-row>
							</view>
						</view>
						<view class="button-group">
							<button type="primary" size="mini" @click="$refs.reportLsitDialog.close()"
								plain="true">关闭</button>
						</view>
					</uni-section>
				</view>
			</uni-popup>
		</view>
		<view>
			<uni-popup ref="filePopupShow">
				<uni-card>
					<view v-for="(item,index) in fileList">
						<el-row>
							<a :href="item" target="_blank">{{item}}</a>
						</el-row>
					</view>
				</uni-card>
			</uni-popup>
		</view>

		<reportQualityForm ref="reportQualityForm"> </reportQualityForm>
		<proPickForm ref="proPickForm"> </proPickForm>
		<manufactureIntoForm ref="manufactureIntoForm"> </manufactureIntoForm>
		<pdaScan></pdaScan>
	</view>
</template>

<script>
	import {
		getStation
	} from "@/api/masterdata/station";
	import {
		listForMobile,
		getInfoByEntryId,
		getWorkOrder
	} from "@/api/production/workOrder";
	import {
		mobileBindUserStation,
		getInfoByUserId
	} from "@/api/common/sysUserStation";
	import storage from '@/utils/storage'
	import {
		scanCodeBindStation
	} from '@/utils/mesUntil.js'
	import {
		listReport,
		getReport,
		delReport,
		addReport,
		updateReport,
		batchSave
	} from "@/api/production/report";
	import {
		getUserProfile
	} from "@/api/system/user"
	import reportQualityForm from "@/pages/quality/reportQuality/form.vue";
	import pdaScan from "@/components/mes/pdaScan.vue"
	import {
		listProPick,
		delProPick,
		addProPick,
		updateProPick
	} from "@/api/warehouse/proPick"
	import proPickForm from "@/pages/warehouse/proPick/form.vue";
	import {
		listManufactureInto,
		getManufactureInto,
		delManufactureInto,
		addManufactureInto,
		updateManufactureInto
	} from "@/api/warehouse/manufactureInto.js"
	import manufactureIntoForm from "@/pages/warehouse/manufactureInto/form.vue";
	import {
		listFieldExtend
	} from "@/api/system/fieldExtend";
	import {
		getMaterial
	} from "@/api/masterdata/material";
	import {
		getUnit
	} from '@/api/masterdata/unit'
	import {
		listWarehouse
	} from "@/api/warehouse/warehouse";
	import {
		getConfigKey
	} from "@/api/system/config";
	import {
		listWarehouseStation,
		getWarehouseStation,
		delWarehouseStation,
		addWarehouseStation
	} from "@/api/warehouse/warehouseStation";

	export default {
		onLoad: function(option) {
			this.workOrder.id = option.id;
		},
		components: {
			reportQualityForm,
			pdaScan,
			proPickForm,
			manufactureIntoForm
		},
		data() {
			return {
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					orderByColumn: '',
					isAsc: "",
					/* 移动端用的工单状态,与字典中稍有差异 */
					mobileStatus: "B",
				},
				// 工单
				workOrder: {
					id: "",
					workOrderEntryList: [],

				},
				//领料任务
				prickEntryList: [

				],
				//报工任务
				reportEntryList: [

				],
				//新增报工单
				report: {
					reportTime: new Date(),
					snArray: ''
				},
				user: {},
				stationId: null,
				scanShow: false,
				reportList: [],
				fileList: [],
				entryFieldExtendList: [],
				warehouseList: [],
				manufactureInto: {
					warehouseId: "",
					warehouseName: "",
				},
			}
		},
		onShow: function() {},
		created() {
			this.getWarehouse();
			this.getSysUserStationList();
			this.getFieldExtendList();
			this.getList();
			this.getUser();
		},
		methods: {
			/** 查询工单主表信息 */
			getList() {
				getWorkOrder(this.workOrder.id).then(response => {

					let stationId = this.stationId;
					this.workOrder = response.data;

					let isShowFlag = true;
					//非生产状态隐藏报工单按钮，并且具有该工位权限才允许报工
					if (this.workOrder.proStatus != "B") {
						isShowFlag = false
					}

					this.prickEntryList = [];
					this.reportEntryList = [];
					console.log("this.workOrder.workOrderEntryList===>", this.workOrder.workOrderEntryList)
					for (var i = 0; i < this.workOrder.workOrderEntryList.length; i++) {
						if (i == 0) {
							this.workOrder.processName = this.workOrder.workOrderEntryList[i].processName;
						}

						let workOrderEntry = this.workOrder.workOrderEntryList[i];
						if (workOrderEntry.stationId == stationId && isShowFlag == true) {
							workOrderEntry.isShow = true;
						} else {
							workOrderEntry.isShow = false;
						}

						//将子表分为领料和报工
						if (workOrderEntry.type == 'pick') {

							this.prickEntryList.push(workOrderEntry);
						}
						if (workOrderEntry.type == 'report') {

							this.reportEntryList.push(workOrderEntry);
						}
					}
				});
			},
			reset() {

			},
			getSysUserStationList() {
				getInfoByUserId().then(response => {
					this.stationId = response.data.stationId
				});
			},
			getUser() {
				getUserProfile().then(response => {
					this.user = response.data
				})
			},
			inputDialogToggle(entry) {
				getInfoByUserId().then(response => {
					console.log("entry=========>", entry)
					this.report.workOrderEntryId = entry.id;
					this.report.reportChannel = 'MOBILE';
					this.report.reportUserId = this.user.userId;
					this.report.reportUserName = this.user.nickName;
					this.report.workshopId = response.data.workshopId;
					this.report.workshopName = response.data.workshopName;
					this.report.stationId = response.data.stationId;
					this.report.stationName = response.data.stationName;
					this.report.processName = entry.processName;
					this.report.reportMaterialName = entry.reportMaterialName;
					this.report.reportSpecification = entry.reportSpecification;
					this.report.materialId = entry.reportMaterialId;
					this.report.materialName = entry.reportMaterialName;
					//质检类型A为免检
					//质检状态A为免检，B为待检验；当质检类型不为A时，质检状态都为B
					this.report.qualityStatus = entry.qcType === "A" ? "A" : "B"
					this.report.reportQuantity = 1;
					this.report.snArray = '';
					this.manufactureInto.workOrderEntryId = entry.id;
					this.$refs.inputDialog.open()
					this.$forceUpdate();
					var _this = this
					uni.$off('scancodedate') // 每次进来先 移除全局自定义事件监听器  
					uni.$on('scancodedate', function(data) {
						_this.report.snArray += "'" + data.code + "',";
						let arr = _this.report.snArray.split(",")
						if (arr.length % 2 != 0) {
							_this.report.snArray += "\r\n"
						}
						console.log('你想要的code1111：', _this.report)
						_this.$forceUpdate;
					})
				});
			},

			submit(ref) {
				this.$refs[ref].validate().then(res => {

					//不使用系统自带的校验功能
					if (this.report.reportQuantity == "" || this.report.reportQuantity <= 0) {
						this.$modal.msgError("请输入报工数量");
						return;
					}
					if (this.manufactureInto.warehouseId == "") {
						this.$modal.msgError("请选择入库仓库");
						return;
					}
					this.reportAdd();

				}).catch(err => {
					console.log('err', err);
				})
			},
			cancel() {
				this.$refs.inputDialog.close();
			},
			//点击新增质检
			addReportQuality(report) {
				this.$refs.reportQualityForm.openPopup(report);
			},
			setScanShow() {
				if (this.scanShow == true) {
					this.scanShow = false;
				} else {
					this.scanShow = true;
				}
			},
			clickReportListPopup(entryId) {
				console.log("entryId======>", entryId)
				listReport({
					pageSize: 99999,
					workOrderEntryId: entryId
				}).then(reportResponse => {
					this.reportList = reportResponse.rows
				})
				this.$refs.reportLsitDialog.open();
			},
			clickPick(entryId) {
				uni.navigateTo({
					url: '/pages/warehouse/proPick/index?workOrderEntryId=' + entryId
				});
			},
			clickInto(entryId) {
				uni.navigateTo({
					url: '/pages/warehouse/manufactureInto/index?workOrderEntryId=' + entryId
				});
			},
			fileDownload(row) {
				let annex = row.annex;
				this.fileList = annex.split(",");
				this.$refs.filePopupShow.open();
			},
			chickDownload(url) {
				uni.downloadFile({
					url: url, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('下载成功');
						}
					}
				});
			},
			getFieldExtendList() {
				//扩展字段结构
				listFieldExtend({
					pageSize: 99999,
					sourceBill: 'process-9'
				}).then(response => {
					this.entryFieldExtendList = response.rows;
				});
			},
			getWarehouse() {
				//判断是否允许跨区域报工
				getConfigKey("mes.pro.allowCrossReport").then(res => {
					var msg = res.msg
					if ("false" === msg) {
						//判断当前报工仓库，是否绑定当前工位
						getInfoByUserId().then(response => {
							let stationId = response.data.stationId;
							listWarehouseStation({
								stationId: stationId
							}).then(res => {
								let list = res.rows;
								this.warehouseList =[];
								for (var i = 0; i < list.length; i++) {
									if (stationId === list[i].stationId) {
										let warehouse= list[i].warehouse;
										warehouse.value=warehouse.id;
										warehouse.text =warehouse.name;
										this.warehouseList.push(warehouse)
									}
								}
							})
						});
					} else {
						listWarehouse({
							pageSize: 99999
						}).then(response => {
							let list = [];
							list = response.rows;
							for (let i = 0; i < list.length; i++) {
								list[i].value = list[i].id;
								list[i].text = list[i].name;
								this.warehouseList.push(list[i]);
							}
						});
					}
				})

			},
			selectWarehouse(id) {
				let opt = {};
				opt = this.warehouseList.find((item) => {
					return item.id === id;
				});
				this.manufactureInto.warehouseName = opt.name;
			},
			reportAdd() {
				let list = [];
				this.report.reportTime = new Date(this.report.reportTime).format(
					"yyyy-MM-dd HH:mm:ss")
				this.report.specification = this.report.reportSpecification;
				list.push(this.report)
				addReport(list).then(response => {
					let _this = this;
					if (_this.manufactureInto.warehouseId != "") {
						//封装入库单
						getInfoByEntryId(_this.manufactureInto.workOrderEntryId).then(
							res => {
								let entry = res.data.workOrderEntryList[0];
								getMaterial(entry.reportMaterialId).then(resB => {
									getUnit(resB.data.unitId).then(
										resC => {
											_this.manufactureInto
												.delivererId = _this
												.user
												.userId;
											_this.manufactureInto
												.delivererName = _this
												.user
												.nickName;
											_this.manufactureInto
												.intoDate = _this
												.report
												.reportTime;
											_this.manufactureInto
												.manufactureIntoEntryList = [{
													materialId: entry
														.reportMaterialId,
													materialName: entry
														.reportMaterialName,
													materialNumber: resB
														.data
														.number,
													materialUnitId: resB
														.data
														.unitId,
													materialUnitName: resC
														.data.name,
													quantity: this
														.report
														.reportQuantity,
													specification: _this
														.report
														.reportSpecification,
													extendFieldJson: entry
														.extendFieldJson
												}];
											addManufactureInto(_this
													.manufactureInto)
												.then(
													resD => {
														console.log(
															"_this.manufactureInto===》",
															_this
															.manufactureInto
														)
													})
										})
								})
							})
					}

					uni.showToast({
						title: `新增成功`
					})
					this.$refs.inputDialog.close();
				});
			}

		},

	}
</script>

<style>
	.resourceList-uni-row {
		margin-bottom: 12rpx;
	}

	.resourceList-text {
		font-size: 16px;
	}

	.resourceList {
		margin-left: 30rpx;
	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.button-group {
		margin-top: 15px;
		display: flex;
		justify-content: space-around;
	}
</style>